package com.wang.net;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.junit.Test;

import com.google.common.io.CharStreams;

public class ProxyClient {

	private static final InetSocketAddress proxyAddr = new InetSocketAddress("192.168.91.11", 80);
	
	 private static final String url = "http://www.baidu.com/";
	 
	 private static List<Proxy> proxies = new ArrayList<>();
	 
	static {
		proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.91.11", 80)));
		proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.91.12", 80)));
	}
	 
	 
	@Test
	public void test() throws Exception{
	
		Proxy proxy = new Proxy(Proxy.Type.HTTP,proxyAddr);		
		URLConnection conn = new URL(url).openConnection(proxy);		
		Reader reader = new InputStreamReader(conn.getInputStream());
		String result = CharStreams.toString(reader);
		System.out.println(result);		
				
	}
	
	
	
	//ProxySelector
	//直接使用Proxy每次连接都需显示指定Proxy,而ProxySelector提供了每次打开连接都具有默认代理的方法:
	
	
	@Test
	public void test2() throws Exception{
		ProxySelector.setDefault(new ProxySelector() {			
			@Override
			public List<Proxy> select(URI uri) {
				String scheme = uri.getScheme();
				System.out.println(scheme);
				if(scheme.equalsIgnoreCase("HTTP")){
					return 	Collections.singletonList(proxies.get(0));
				}else{
					return 	Collections.singletonList(proxies.get(1));
				}
			}
			
			@Override
			public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {				
				System.out.println(String.format("uri:%s, socketAddress:%s ", uri,sa));
			}
		});
		
		URLConnection connection = new URL(url).openConnection();
		Reader reader = new InputStreamReader(connection.getInputStream());
		String content = CharStreams.toString(reader);
		System.out.println(content);
		
		
		
	}
	
	
	
	
	
	
	
	
	
	
}
